package com.datagateway.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 报表生成器
 * 负责生成各种格式的统计报表，支持HTML、PDF、Excel等格式
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@Component
public class ReportGenerator {

    private static final Logger logger = LoggerFactory.getLogger(ReportGenerator.class);

    @Autowired
    private DataStatisticsManager dataStatisticsManager;

    @Autowired
    private AlertManager alertManager;

    /**
     * 报表生成配置
     */
    private String reportOutputPath = "reports";
    private boolean autoGenerateReports = true;
    private String reportFormat = "HTML";
    private String reportTemplate = "default";
    private boolean includeCharts = true;
    private String reportTitle = "Data Gateway Statistics Report";

    /**
     * 执行器
     */
    private final ExecutorService reportExecutor = Executors.newFixedThreadPool(3, r -> {
        Thread t = new Thread(r, "report-generator");
        t.setDaemon(true);
        return t;
    });

    /**
     * 日期格式化器
     */
    private final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
    private final SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 初始化报表生成器
     */
    public void initialize() {
        try {
            // 创建报表输出目录
            createReportDirectory();
            
            logger.info("报表生成器初始化成功");
            
        } catch (Exception e) {
            logger.error("报表生成器初始化失败", e);
            alertManager.sendSystemErrorAlert("报表生成器初始化失败", e.getMessage());
        }
    }

    /**
     * 停止报表生成器
     */
    public void stop() {
        try {
            reportExecutor.shutdown();
            if (!reportExecutor.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS)) {
                reportExecutor.shutdownNow();
            }
            
            logger.info("报表生成器停止成功");
            
        } catch (Exception e) {
            logger.error("报表生成器停止失败", e);
        }
    }

    /**
     * 生成系统统计报表
     * 
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateSystemReport(String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                DataStatisticsManager.SystemStatistics stats = dataStatisticsManager.getSystemStatistics();
                return generateReport("system", stats, format);
            } catch (Exception e) {
                logger.error("生成系统统计报表失败", e);
                throw new RuntimeException("生成系统统计报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成日报表
     * 
     * @param date 日期
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateDailyReport(Date date, String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                DataStatisticsManager.DailyReport report = dataStatisticsManager.generateDailyReport(date);
                return generateReport("daily", report, format);
            } catch (Exception e) {
                logger.error("生成日报表失败: {}", date, e);
                throw new RuntimeException("生成日报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成周报表
     * 
     * @param weekStartDate 周开始日期
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateWeeklyReport(Date weekStartDate, String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                DataStatisticsManager.WeeklyReport report = dataStatisticsManager.generateWeeklyReport(weekStartDate);
                return generateReport("weekly", report, format);
            } catch (Exception e) {
                logger.error("生成周报表失败: {}", weekStartDate, e);
                throw new RuntimeException("生成周报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成月报表
     * 
     * @param month 月份
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateMonthlyReport(Date month, String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                DataStatisticsManager.MonthlyReport report = dataStatisticsManager.generateMonthlyReport(month);
                return generateReport("monthly", report, format);
            } catch (Exception e) {
                logger.error("生成月报表失败: {}", month, e);
                throw new RuntimeException("生成月报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成业务统计报表
     * 
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateBusinessReport(String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                List<DataStatisticsManager.BusinessStatistics> businessStats = dataStatisticsManager.getBusinessStatistics();
                return generateReport("business", businessStats, format);
            } catch (Exception e) {
                logger.error("生成业务统计报表失败", e);
                throw new RuntimeException("生成业务统计报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成性能统计报表
     * 
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generatePerformanceReport(String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                DataStatisticsManager.PerformanceStatistics perfStats = dataStatisticsManager.getPerformanceStatistics();
                return generateReport("performance", perfStats, format);
            } catch (Exception e) {
                logger.error("生成性能统计报表失败", e);
                throw new RuntimeException("生成性能统计报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成时间窗口统计报表
     * 
     * @param timeWindow 时间窗口（分钟）
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateTimeWindowReport(int timeWindow, String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                List<DataStatisticsManager.TimeWindowStatistics> timeStats = 
                    dataStatisticsManager.getTimeWindowStatistics(timeWindow);
                return generateReport("timewindow", timeStats, format);
            } catch (Exception e) {
                logger.error("生成时间窗口统计报表失败", e);
                throw new RuntimeException("生成时间窗口统计报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 生成综合报表
     * 
     * @param format 报表格式
     * @return 报表文件路径
     */
    public CompletableFuture<String> generateComprehensiveReport(String format) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ComprehensiveReportData reportData = new ComprehensiveReportData();
                reportData.systemStats = dataStatisticsManager.getSystemStatistics();
                reportData.businessStats = dataStatisticsManager.getBusinessStatistics();
                reportData.performanceStats = dataStatisticsManager.getPerformanceStatistics();
                reportData.timeWindowStats = dataStatisticsManager.getTimeWindowStatistics(60); // 1小时窗口
                
                return generateReport("comprehensive", reportData, format);
            } catch (Exception e) {
                logger.error("生成综合报表失败", e);
                throw new RuntimeException("生成综合报表失败", e);
            }
        }, reportExecutor);
    }

    /**
     * 获取报表列表
     * 
     * @return 报表文件列表
     */
    public List<ReportFile> getReportList() {
        try {
            List<ReportFile> reports = new ArrayList<>();
            Path reportDir = Paths.get(reportOutputPath);
            
            if (Files.exists(reportDir)) {
                Files.walk(reportDir)
                    .filter(Files::isRegularFile)
                    .forEach(path -> {
                        try {
                            ReportFile report = new ReportFile(
                                path.getFileName().toString(),
                                path.toString(),
                                Files.size(path),
                                Files.getLastModifiedTime(path).toMillis()
                            );
                            reports.add(report);
                        } catch (IOException e) {
                            logger.error("获取报表文件信息失败: {}", path, e);
                        }
                    });
            }
            
            // 按修改时间排序
            reports.sort(Comparator.comparing(ReportFile::getLastModified).reversed());
            
            return reports;
            
        } catch (Exception e) {
            logger.error("获取报表列表失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 删除报表文件
     * 
     * @param fileName 文件名
     * @return 是否删除成功
     */
    public boolean deleteReport(String fileName) {
        try {
            Path filePath = Paths.get(reportOutputPath, fileName);
            if (Files.exists(filePath)) {
                Files.delete(filePath);
                logger.info("报表文件删除成功: {}", fileName);
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("删除报表文件失败: {}", fileName, e);
            return false;
        }
    }

    /**
     * 设置报表生成配置
     * 
     * @param outputPath 输出路径
     * @param autoGenerate 自动生成
     * @param format 格式
     * @param template 模板
     * @param includeCharts 包含图表
     * @param title 标题
     */
    public void setConfiguration(String outputPath, boolean autoGenerate, String format,
                               String template, boolean includeCharts, String title) {
        this.reportOutputPath = outputPath;
        this.autoGenerateReports = autoGenerate;
        this.reportFormat = format;
        this.reportTemplate = template;
        this.includeCharts = includeCharts;
        this.reportTitle = title;
        
        // 创建输出目录
        createReportDirectory();
        
        logger.info("报表生成配置已更新: 输出路径={}, 自动生成={}, 格式={}, 模板={}, 图表={}, 标题={}", 
                   outputPath, autoGenerate, format, template, includeCharts, title);
    }

    /**
     * 生成报表
     */
    private String generateReport(String reportType, Object data, String format) {
        try {
            String fileName = generateFileName(reportType, format);
            String filePath = Paths.get(reportOutputPath, fileName).toString();
            
            switch (format.toUpperCase()) {
                case "HTML":
                    generateHtmlReport(data, filePath, reportType);
                    break;
                case "JSON":
                    generateJsonReport(data, filePath);
                    break;
                case "CSV":
                    generateCsvReport(data, filePath, reportType);
                    break;
                case "TXT":
                    generateTextReport(data, filePath, reportType);
                    break;
                default:
                    throw new IllegalArgumentException("不支持的报表格式: " + format);
            }
            
            logger.info("报表生成成功: {}", filePath);
            return filePath;
            
        } catch (Exception e) {
            logger.error("生成报表失败: type={}, format={}", reportType, format, e);
            throw new RuntimeException("生成报表失败", e);
        }
    }

    /**
     * 生成HTML报表
     */
    private void generateHtmlReport(Object data, String filePath, String reportType) throws IOException {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, java.nio.charset.StandardCharsets.UTF_8))) {
            writer.println("<!DOCTYPE html>");
            writer.println("<html lang=\"zh-CN\">");
            writer.println("<head>");
            writer.println("    <meta charset=\"UTF-8\">");
            writer.println("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
            writer.println("    <title>" + reportTitle + "</title>");
            writer.println("    <style>");
            writer.println(getHtmlStyles());
            writer.println("    </style>");
            writer.println("</head>");
            writer.println("<body>");
            writer.println("    <div class=\"container\">");
            writer.println("        <header>");
            writer.println("            <h1>" + reportTitle + "</h1>");
            writer.println("            <p class=\"report-info\">报表类型: " + reportType + " | 生成时间: " + 
                          timeFormatter.format(new Date()) + "</p>");
            writer.println("        </header>");
            
            writer.println("        <main>");
            generateHtmlContent(writer, data, reportType);
            writer.println("        </main>");
            
            writer.println("        <footer>");
            writer.println("            <p>Generated by Data Gateway Report Generator</p>");
            writer.println("        </footer>");
            writer.println("    </div>");
            writer.println("</body>");
            writer.println("</html>");
        }
    }

    /**
     * 生成JSON报表
     */
    private void generateJsonReport(Object data, String filePath) throws IOException {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, java.nio.charset.StandardCharsets.UTF_8))) {
            // 这里可以使用JSON库来序列化对象
            // 简化实现：直接输出对象信息
            writer.println("{");
            writer.println("  \"reportType\": \"" + data.getClass().getSimpleName() + "\",");
            writer.println("  \"generatedTime\": \"" + timeFormatter.format(new Date()) + "\",");
            writer.println("  \"data\": \"" + data.toString() + "\"");
            writer.println("}");
        }
    }

    /**
     * 生成CSV报表
     */
    private void generateCsvReport(Object data, String filePath, String reportType) throws IOException {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, java.nio.charset.StandardCharsets.UTF_8))) {
            writer.println("Report Type,Generated Time,Data");
            writer.println("\"" + reportType + "\",\"" + timeFormatter.format(new Date()) + "\",\"" + 
                          data.toString().replace("\"", "\"\"") + "\"");
        }
    }

    /**
     * 生成文本报表
     */
    private void generateTextReport(Object data, String filePath, String reportType) throws IOException {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, java.nio.charset.StandardCharsets.UTF_8))) {
            writer.println("=".repeat(60));
            writer.println(reportTitle);
            writer.println("=".repeat(60));
            writer.println("报表类型: " + reportType);
            writer.println("生成时间: " + timeFormatter.format(new Date()));
            writer.println("-".repeat(60));
            writer.println(data.toString());
            writer.println("=".repeat(60));
        }
    }

    /**
     * 生成HTML内容
     */
    private void generateHtmlContent(PrintWriter writer, Object data, String reportType) {
        if (data instanceof DataStatisticsManager.SystemStatistics) {
            generateSystemStatsHtml(writer, (DataStatisticsManager.SystemStatistics) data);
        } else if (data instanceof DataStatisticsManager.DailyReport) {
            generateDailyReportHtml(writer, (DataStatisticsManager.DailyReport) data);
        } else if (data instanceof DataStatisticsManager.WeeklyReport) {
            generateWeeklyReportHtml(writer, (DataStatisticsManager.WeeklyReport) data);
        } else if (data instanceof DataStatisticsManager.MonthlyReport) {
            generateMonthlyReportHtml(writer, (DataStatisticsManager.MonthlyReport) data);
        } else if (data instanceof List) {
            generateListStatsHtml(writer, (List<?>) data, reportType);
        } else if (data instanceof ComprehensiveReportData) {
            generateComprehensiveReportHtml(writer, (ComprehensiveReportData) data);
        } else {
            writer.println("        <div class=\"content\">");
            writer.println("            <pre>" + data.toString() + "</pre>");
            writer.println("        </div>");
        }
    }

    /**
     * 生成系统统计HTML
     */
    private void generateSystemStatsHtml(PrintWriter writer, DataStatisticsManager.SystemStatistics stats) {
        writer.println("        <div class=\"stats-grid\">");
        writer.println("            <div class=\"stat-card\">");
        writer.println("                <h3>总处理量</h3>");
        writer.println("                <div class=\"stat-value\">" + stats.getTotalProcessed() + "</div>");
        writer.println("            </div>");
        writer.println("            <div class=\"stat-card\">");
        writer.println("                <h3>成功率</h3>");
        writer.println("                <div class=\"stat-value\">" + String.format("%.2f%%", stats.getSuccessRate() * 100) + "</div>");
        writer.println("            </div>");
        writer.println("            <div class=\"stat-card\">");
        writer.println("                <h3>平均处理时间</h3>");
        writer.println("                <div class=\"stat-value\">" + String.format("%.2f ms", stats.getAverageProcessingTime()) + "</div>");
        writer.println("            </div>");
        writer.println("            <div class=\"stat-card\">");
        writer.println("                <h3>总数据量</h3>");
        writer.println("                <div class=\"stat-value\">" + formatDataSize(stats.getTotalDataSize()) + "</div>");
        writer.println("            </div>");
        writer.println("        </div>");
    }

    /**
     * 生成日报表HTML
     */
    private void generateDailyReportHtml(PrintWriter writer, DataStatisticsManager.DailyReport report) {
        writer.println("        <div class=\"report-section\">");
        writer.println("            <h2>日报表 - " + dateFormatter.format(report.getDate()) + "</h2>");
        writer.println("            <div class=\"stats-grid\">");
        writer.println("                <div class=\"stat-card\">");
        writer.println("                    <h3>处理量</h3>");
        writer.println("                    <div class=\"stat-value\">" + report.getProcessedCount() + "</div>");
        writer.println("                </div>");
        writer.println("                <div class=\"stat-card\">");
        writer.println("                    <h3>成功率</h3>");
        writer.println("                    <div class=\"stat-value\">" + String.format("%.2f%%", report.getSuccessRate() * 100) + "</div>");
        writer.println("                </div>");
        writer.println("            </div>");
        writer.println("        </div>");
    }

    /**
     * 生成周报表HTML
     */
    private void generateWeeklyReportHtml(PrintWriter writer, DataStatisticsManager.WeeklyReport report) {
        writer.println("        <div class=\"report-section\">");
        writer.println("            <h2>周报表 - " + dateFormatter.format(report.getWeekStartDate()) + "</h2>");
        writer.println("            <div class=\"stats-grid\">");
        writer.println("                <div class=\"stat-card\">");
        writer.println("                    <h3>处理量</h3>");
        writer.println("                    <div class=\"stat-value\">" + report.getProcessedCount() + "</div>");
        writer.println("                </div>");
        writer.println("                <div class=\"stat-card\">");
        writer.println("                    <h3>成功率</h3>");
        writer.println("                    <div class=\"stat-value\">" + String.format("%.2f%%", report.getSuccessRate() * 100) + "</div>");
        writer.println("                </div>");
        writer.println("            </div>");
        writer.println("        </div>");
    }

    /**
     * 生成月报表HTML
     */
    private void generateMonthlyReportHtml(PrintWriter writer, DataStatisticsManager.MonthlyReport report) {
        writer.println("        <div class=\"report-section\">");
        writer.println("            <h2>月报表 - " + dateFormatter.format(report.getMonth()) + "</h2>");
        writer.println("            <div class=\"stats-grid\">");
        writer.println("                <div class=\"stat-card\">");
        writer.println("                    <h3>处理量</h3>");
        writer.println("                    <div class=\"stat-value\">" + report.getProcessedCount() + "</div>");
        writer.println("                </div>");
        writer.println("                <div class=\"stat-card\">");
        writer.println("                    <h3>成功率</h3>");
        writer.println("                    <div class=\"stat-value\">" + String.format("%.2f%%", report.getSuccessRate() * 100) + "</div>");
        writer.println("                </div>");
        writer.println("            </div>");
        writer.println("        </div>");
    }

    /**
     * 生成列表统计HTML
     */
    private void generateListStatsHtml(PrintWriter writer, List<?> data, String reportType) {
        writer.println("        <div class=\"report-section\">");
        writer.println("            <h2>" + reportType + " 统计</h2>");
        writer.println("            <table class=\"stats-table\">");
        writer.println("                <thead>");
        writer.println("                    <tr>");
        writer.println("                        <th>项目</th>");
        writer.println("                        <th>值</th>");
        writer.println("                    </tr>");
        writer.println("                </thead>");
        writer.println("                <tbody>");
        
        for (Object item : data) {
            writer.println("                    <tr>");
            writer.println("                        <td>" + item.getClass().getSimpleName() + "</td>");
            writer.println("                        <td>" + item.toString() + "</td>");
            writer.println("                    </tr>");
        }
        
        writer.println("                </tbody>");
        writer.println("            </table>");
        writer.println("        </div>");
    }

    /**
     * 生成综合报表HTML
     */
    private void generateComprehensiveReportHtml(PrintWriter writer, ComprehensiveReportData data) {
        generateSystemStatsHtml(writer, data.systemStats);
        generateListStatsHtml(writer, data.businessStats, "业务统计");
        generateListStatsHtml(writer, data.timeWindowStats, "时间窗口统计");
    }

    /**
     * 生成文件名
     */
    private String generateFileName(String reportType, String format) {
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return String.format("%s_%s.%s", reportType, timestamp, format.toLowerCase());
    }

    /**
     * 创建报表目录
     */
    private void createReportDirectory() {
        try {
            Path reportDir = Paths.get(reportOutputPath);
            if (!Files.exists(reportDir)) {
                Files.createDirectories(reportDir);
                logger.info("创建报表目录: {}", reportOutputPath);
            }
        } catch (Exception e) {
            logger.error("创建报表目录失败: {}", reportOutputPath, e);
        }
    }

    /**
     * 格式化数据大小
     */
    private String formatDataSize(long bytes) {
        if (bytes < 1024) return bytes + " B";
        if (bytes < 1024 * 1024) return String.format("%.2f KB", bytes / 1024.0);
        if (bytes < 1024 * 1024 * 1024) return String.format("%.2f MB", bytes / (1024.0 * 1024.0));
        return String.format("%.2f GB", bytes / (1024.0 * 1024.0 * 1024.0));
    }

    /**
     * 获取HTML样式
     */
    private String getHtmlStyles() {
        return "body {\n" +
            "    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n" +
            "    margin: 0;\n" +
            "    padding: 20px;\n" +
            "    background-color: #f5f5f5;\n" +
            "    color: #333;\n" +
            "}\n" +
            ".container {\n" +
            "    max-width: 1200px;\n" +
            "    margin: 0 auto;\n" +
            "    background: white;\n" +
            "    border-radius: 8px;\n" +
            "    box-shadow: 0 2px 10px rgba(0,0,0,0.1);\n" +
            "    overflow: hidden;\n" +
            "}\n" +
            "header {\n" +
            "    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n" +
            "    color: white;\n" +
            "    padding: 30px;\n" +
            "    text-align: center;\n" +
            "}\n" +
            "header h1 {\n" +
            "    margin: 0;\n" +
            "    font-size: 2.5em;\n" +
            "    font-weight: 300;\n" +
            "}\n" +
            ".report-info {\n" +
            "    margin: 10px 0 0 0;\n" +
            "    opacity: 0.9;\n" +
            "    font-size: 1.1em;\n" +
            "}\n" +
            "main {\n" +
            "    padding: 30px;\n" +
            "}\n" +
            ".stats-grid {\n" +
            "    display: grid;\n" +
            "    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n" +
            "    gap: 20px;\n" +
            "    margin: 20px 0;\n" +
            "}\n" +
            ".stat-card {\n" +
            "    background: #f8f9fa;\n" +
            "    border-radius: 8px;\n" +
            "    padding: 20px;\n" +
            "    text-align: center;\n" +
            "    border-left: 4px solid #667eea;\n" +
            "}\n" +
            ".stat-card h3 {\n" +
            "    margin: 0 0 10px 0;\n" +
            "    color: #666;\n" +
            "    font-size: 1em;\n" +
            "    font-weight: 500;\n" +
            "}\n" +
            ".stat-value {\n" +
            "    font-size: 2em;\n" +
            "    font-weight: bold;\n" +
            "    color: #333;\n" +
            "}\n" +
            ".report-section {\n" +
            "    margin: 30px 0;\n" +
            "}\n" +
            ".report-section h2 {\n" +
            "    color: #333;\n" +
            "    border-bottom: 2px solid #667eea;\n" +
            "    padding-bottom: 10px;\n" +
            "}\n" +
            ".stats-table {\n" +
            "    width: 100%;\n" +
            "    border-collapse: collapse;\n" +
            "    margin: 20px 0;\n" +
            "}\n" +
            ".stats-table th,\n" +
            ".stats-table td {\n" +
            "    padding: 12px;\n" +
            "    text-align: left;\n" +
            "    border-bottom: 1px solid #ddd;\n" +
            "}\n" +
            ".stats-table th {\n" +
            "    background-color: #f8f9fa;\n" +
            "    font-weight: 600;\n" +
            "    color: #333;\n" +
            "}\n" +
            ".stats-table tr:hover {\n" +
            "    background-color: #f5f5f5;\n" +
            "}\n" +
            "footer {\n" +
            "    background: #f8f9fa;\n" +
            "    padding: 20px;\n" +
            "    text-align: center;\n" +
            "    color: #666;\n" +
            "    border-top: 1px solid #eee;\n" +
            "}";
    }

    /**
     * 综合报表数据类
     */
    public static class ComprehensiveReportData {
        public DataStatisticsManager.SystemStatistics systemStats;
        public List<DataStatisticsManager.BusinessStatistics> businessStats;
        public DataStatisticsManager.PerformanceStatistics performanceStats;
        public List<DataStatisticsManager.TimeWindowStatistics> timeWindowStats;
    }

    /**
     * 报表文件类
     */
    public static class ReportFile {
        private final String fileName;
        private final String filePath;
        private final long fileSize;
        private final long lastModified;

        public ReportFile(String fileName, String filePath, long fileSize, long lastModified) {
            this.fileName = fileName;
            this.filePath = filePath;
            this.fileSize = fileSize;
            this.lastModified = lastModified;
        }

        // Getter方法
        public String getFileName() { return fileName; }
        public String getFilePath() { return filePath; }
        public long getFileSize() { return fileSize; }
        public long getLastModified() { return lastModified; }
        
        public String getFormattedFileSize() {
            if (fileSize < 1024) return fileSize + " B";
            if (fileSize < 1024 * 1024) return String.format("%.2f KB", fileSize / 1024.0);
            if (fileSize < 1024 * 1024 * 1024) return String.format("%.2f MB", fileSize / (1024.0 * 1024.0));
            return String.format("%.2f GB", fileSize / (1024.0 * 1024.0 * 1024.0));
        }
        
        public String getFormattedLastModified() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(lastModified));
        }
    }
}
